package com.arpa.ntocc.basic.api.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.RestFulStatus;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.LogUtil;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.controller.BaseController;
import com.arpa.ntocc.common.domain.dto.ShipmentAuthorizationJsonBean;
import com.arpa.ntocc.common.domain.dto.ShipmentDTO;
import com.arpa.ntocc.common.domain.dto.ShipmentFromDTO;
import com.arpa.ntocc.common.domain.entity.Client;
import com.arpa.ntocc.common.domain.entity.Shipment;
import com.arpa.ntocc.common.domain.entity.UserLogin;
import com.arpa.ntocc.common.domain.enums.ClientTypeEnum;
import com.arpa.ntocc.common.domain.vo.ShipmentVO;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.ntocc.common.security.annotation.NoRepeat;
import com.arpa.ntocc.common.service.IClientService;
import com.arpa.ntocc.common.service.IShipmentService;
import com.arpa.ntocc.common.service.IUserLoginService;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 入驻商
 * </p>
 *
 * @author LEO
 * @since 2019-12-19
 */
@Api(tags = "入驻商管理")
@RestController
@RequestMapping(value = "/shipment", produces = "application/json;charset=UTF-8")
@Log4j2
public class ShipmentController extends BaseController {

    private final IShipmentService iShipmentService;
    private final IClientService clientService;
    private final IUserLoginService userLoginService;

    public ShipmentController(IShipmentService iShipmentService,
                              IClientService clientService,
                              IUserLoginService userLoginService) {
        this.iShipmentService = iShipmentService;
        this.clientService = clientService;
        this.userLoginService = userLoginService;
    }

    /**
     * 获取 托运方 列表
     *
     * @param shipmentDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取入驻商列表", notes = "获取入驻商列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = ShipmentVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(ShipmentDTO shipmentDTO, HttpServletRequest request) {
        try {
            shipmentDTO.setBranchCode(UserUtil.getBranchCode());
            ShipmentVO shipmentVOSum = iShipmentService.queryListSum(shipmentDTO);
            List<ShipmentVO> shipmentVOList = iShipmentService.queryList(shipmentDTO);

            Page returnPage = new Page(shipmentDTO.getPageNum(), shipmentDTO.getPageSize());
            returnPage.setRecords(shipmentVOList);
            returnPage.setTotal(shipmentVOSum.getTotal());
            returnPage.setSumObject(shipmentVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加入驻商
     *
     * @param entity  Shipment
     * @param request
     * @return
     */
    @ApiOperation(value = "添加入驻商", notes = "添加入驻商")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @NoRepeat(time = 2000)
    @PostMapping()
    public Result create( @RequestBody @Validated(ShipmentFromDTO.Save.class) ShipmentFromDTO entity,
                         HttpServletRequest request) {
        try {
            iShipmentService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }



    /**
     * 获取入驻商详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取入驻商详情", notes = "获取入驻商详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "code", value = "入驻商标识", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = ShipmentVO.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result shipment(@PathVariable String code,HttpServletRequest request) {
        ShipmentVO entity = iShipmentService.getOneInfo(code);
        return Result.ok().data(entity);
    }

    /**
     * 修改托运方
     *
     * @param entity  托运方
     * @param request
     * @return
     */
    @ApiOperation(value = "修改入驻商信息", notes = "修改入驻商信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PutMapping()
    public Result update(@Valid @RequestBody @Validated(ShipmentFromDTO.Update.class) ShipmentFromDTO entity, HttpServletRequest request) {
        if (StringUtils.isBlank(entity.getCode())) {
            return Result.error("code不能为空");
        }
        int updateNum = iShipmentService.updateByCode(entity);
        if (updateNum == 0) {
            return Result.error("没有更新数据！code:" + entity.getCode());
        } else {
            return Result.ok("修改成功,更新" + updateNum + "条数据！");
        }
    }


    /**
     * 删除 托运方
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除入驻商", notes = "删除入驻商 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            iShipmentService.removeShipment(codes);
            return Result.ok("操作成功！");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }





    /**
     * WMS登录时获取授权仓库
     *
     * @param client_id
     * @param client_secret
     * @param userLoginId
     * @param request
     * @return
     */
    @ApiOperation(value = "OMS登录页面获取授权入驻商列表", notes = "仅限OMS登录页面入驻商下拉列表框使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "client_id", value = "客户端ID", required = true, paramType = "header", dataType = "string", defaultValue = ""),
            @ApiImplicitParam(name = "client_secret", value = "客户端安全码", required = true, paramType = "header", dataType = "string", defaultValue = ""),
            @ApiImplicitParam(name = "userLoginId", value = "登录账号", required = true, paramType = "query", dataType = "string", defaultValue = ""),
    })
    @GetMapping("/shipmentAuthorization")
    public Result cascadeData(@RequestHeader String client_id, @RequestHeader String client_secret, @RequestParam String userLoginId, HttpServletRequest request) {
        //校验客户端应用ID和安全码
        Client client = clientService.getClient(client_id, client_secret);
        if (client == null) {
            log.info(LogUtil.log("客户端应用ID【" + client_id + "】和安全码【" + client_secret + "】验证失败！"));
            return Result.error(RestFulStatus.OAUTH2_INVALID_CLIENT);
        }
        UserLogin userLogin = userLoginService.getUserLoginByUserLoginId(userLoginId);
        if(null==userLogin){
            return Result.error("登录账号不存在");
        }
        if (StrUtil.equals(ClientTypeEnum.WEB_OMS.getValue(), client.getType()) && StrUtil.isNotBlank(userLogin.getShipmentAuthorization())) {
            List<ShipmentAuthorizationJsonBean> shipmentAuthorizationJsonBeans = JSONUtil.toList(JSONUtil.parseArray(userLogin.getShipmentAuthorization()), ShipmentAuthorizationJsonBean.class);
            List<Shipment> shipments = shipmentAuthorizationJsonBeans.stream().map(r -> iShipmentService.findShipmentByPartyCode(r.getShipment())).collect(Collectors.toList());
            return Result.ok().data(shipments);
        }
        return Result.ok();
    }

    @ApiOperation(value = "判断货主是否需要复核", notes = "判断货主是否需要复核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(value = "货主编码集合", paramType = "body", dataType = "list", required = true)
    })
    @NeedLogin
    @PostMapping("/judgeRecheck")
    public Result judgeRecheck(@RequestBody List<String> shipmentCodes) {
        return iShipmentService.judgeRecheck(shipmentCodes);
    }

}
